package logic

import (
	"context"
	"errors"
	"short-video-manager/models/cache"
	"short-video-manager/models/mysql"
	"short-video-manager/pkg"

	"short-video-manager/videorpc/internal/svc"
	"short-video-manager/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePwdLogic {
	return &UpdatePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePwdLogic) UpdatePwd(in *videorpc.UpdatePwdRequest) (*videorpc.UpdatePwdResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.UserInfo

	if err := user.FindUserByPhone(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("手机号码不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码不正确")
	}
	if in.Password != in.NewPassword {
		return nil, errors.New("两次输入的密码不一致")
	}
	user.Pwd = pkg.Md5(in.Password)

	if err := user.UpdatePassword(mysql.DB); err != nil {
		return nil, errors.New("修改失败")
	}
	return &videorpc.UpdatePwdResponse{}, nil
}
